package com.pig4cloud.pig.admin.task;

import cn.hutool.core.date.DateUtil;
import com.pig4cloud.pig.admin.api.entity.NewsList;
import com.pig4cloud.pig.admin.constant.CommonConstant;
import com.pig4cloud.pig.admin.task.base.BaseTask;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadLocalRandom;

@Component
public class YuleNews extends BaseTask {
	private String websiteUrl = "http://news.yule.com.cn/neidi/index";

	@Scheduled(cron = "0/5 * * * * ?")
	public void doTask(){
		int randomPage = ThreadLocalRandom.current().nextInt(1, 2914);
		String request = httpUtilService.getRequest(1,this.getClass(), websiteUrl+randomPage+".html", CommonConstant.UTF8);
		Document parse = Jsoup.parse(request);
		Elements select = parse.body().select("#LBMainBody").select("ul").select("li");
		for (Element sele : select) {
			String imgUrl = sele.select("img").attr("src");
			String topic = sele.select(".titname").select("a").text().trim();
			String link = sele.select(".titname").select("a").attr("href");
			String desc = sele.select(".introduce").select("a").text()
					.replaceAll("&nbsp;", "")
					.replaceAll("&ldquo;", "")
					.replaceAll("　　中国娱乐网讯 www yule com cn ", "")
					.replaceAll("　　中国娱乐网讯www yule com cn ", "")
					.replaceAll("　　", "")
					.trim();
			String topic1 = sele.select(".other").select("a").text();
			String time = sele.select(".other").select("#time").text().trim();
			NewsList news = NewsList.create(idGenerator.nextId());
			news.setSubTitle(desc);
			news.setUrl(link);
			news.setCreateTime(DateUtil.parse(time,"yyyy-MM-dd HH:mm:ss"));
			news.setTitle(topic + "-" + topic1);
			news.setImgUrl(imgUrl);
			news.setCategory("娱乐新闻");
			pushNewsToRedis(news);
		}


	}

}
